<template>
    <div class="products-management">
        <div class="page-title">商品管理</div>

        <!-- 操作栏 -->
        <div class="operation-bar">
            <div class="search-box">
                <el-input
                        v-model="searchKeyword"
                        placeholder="搜索商品名称或ID"
                        prefix-icon="Search"
                        class="search-input"
                        @keyup.enter="handleSearch"
                />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div>
            <el-button type="success" @click="handleAdd">添加商品</el-button>
        </div>

        <!-- 商品列表 -->
        <div class="products-table">
            <el-table
                    :data="goodsList"
                    border
                    stripe
                    style="width: 100%"
                    :empty-text="loading ? '加载中...' : '暂无商品数据'"
            >
                <el-table-column prop="productId" label="商品ID" width="100" align="center"/>
                <el-table-column label="商品图片" width="120" align="center">
                    <template #default="scope">
                        <img
                                :src="scope.row.image1 || 'https://picsum.photos/80/80?grayscale'"
                                alt="商品图片"
                                class="product-img"
                        >
                    </template>
                </el-table-column>
                <el-table-column prop="productName" label="商品名称" min-width="180"/>
                <el-table-column prop="listPrice" label="原价" width="100" align="center">
                    <template #default="scope">¥{{ scope.row.listPrice.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="actualPrice" label="售价" width="100" align="center">
                    <template #default="scope">¥{{ scope.row.actualPrice.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" width="100" align="center"/>
                <el-table-column prop="sales" label="销量" width="100" align="center"/>
                <el-table-column prop="listedAt" label="上架时间" width="160" align="center"/>
                <el-table-column label="操作" width="200" align="center">
                    <template #default="scope">
                        <el-button
                                type="primary"
                                size="small"
                                @click="handleEdit(scope.row)"
                                class="btn-edit"
                        >
                            编辑
                        </el-button>
                        <el-button
                                type="danger"
                                size="small"
                                @click="del(scope.row.productId)"
                                class="btn-delete"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                    @current-change="jump"
                    :current-page="pages.page"
                    :page-size="pages.limit"
                    layout="prev, pager, next"
                    :total="totalCount"
                    class="pagination"
            />
        </div>

        <!-- 编辑商品弹窗 -->
        <el-dialog
                v-model="isEditDialogVisible"
                title="编辑商品"
                width="70%"
        >
            <el-form :model="editForm" label-width="100px">
                <el-form-item label="商品名称">
                    <el-input v-model="editForm.productName"/>
                </el-form-item>
                <el-form-item label="原价">
                    <el-input v-model="editForm.listPrice" type="number"/>
                </el-form-item>
                <el-form-item label="售价">
                    <el-input v-model="editForm.actualPrice" type="number"/>
                </el-form-item>
                <el-form-item label="库存">
                    <el-input v-model="editForm.stock" type="number"/>
                </el-form-item>
                <el-form-item label="商品描述">
                    <el-input v-model="editForm.shortDesc" type="textarea" rows="3"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="isEditDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdate">确定</el-button>
            </template>
        </el-dialog>

        <!--        增加商品弹窗-->
        <el-dialog
                v-model="isAddDialogVisible"
                title="添加商品"
                width="70%"
        >
            <el-form :model="addForm" label-width="100px">
                <el-form-item label="商品名称">
                    <el-input v-model="addForm.productName"/>
                </el-form-item>
                <el-form-item label="原价">
                    <el-input v-model="addForm.listPrice" type="number"/>
                </el-form-item>
                <el-form-item label="售价">
                    <el-input v-model="addForm.actualPrice" type="number"/>
                </el-form-item>
                <el-form-item label="库存">
                    <el-input v-model="addForm.stock" type="number"/>
                </el-form-item>
                <el-form-item label="商品描述">
                    <el-input v-model="addForm.shortDesc" type="textarea" rows="3"/>
                </el-form-item>
                <el-form-item label="商品详细描述">
                    <el-input v-model="editForm.longDesc" type="textarea" rows="3"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="isAddDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAddProduct">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import axios from "@/utils/axios.js"
import {onMounted, reactive, ref} from "vue";


const pages = reactive({
    page: 1,
    limit: 6,
})

// 搜索关键词
const searchKeyword = ref('');
// 总条数(实际项目从接口获取)
const totalCount = ref(0);
// 加载状态
const loading = ref(false);
// 编辑弹窗显示状态
const isEditDialogVisible = ref(false);
const isAddDialogVisible = ref(false);

// 添加商品数据
const addForm = reactive({
    productId: '',
    productName: '',
    listPrice: 0,
    actualPrice: 0,
    stock: 0,
    shortDesc: '',
    longDesc: '',
});
// 编辑表单数据
const editForm = reactive({
    productId: '',
    productName: '',
    listPrice: 0,
    actualPrice: 0,
    stock: 0,
    shortDesc: '',
    longDesc: '',
});

onMounted(() => {
    init()
})

const init = () => {
    loading.value = true;
    axios.get("/api/productsPage?page=" + pages.page + "&limit=" + pages.limit)
        .then(res => {
            console.log(res.data)
            goodsList.value = res.data.records || res.data; // 适配不同接口返回格式
            totalCount.value = res.data.total || goodsList.value.length; // 假设接口返回total字段
            loading.value = false;
        })
        .catch(err => {
            console.error('加载商品失败:', err);
            loading.value = false;
            ElMessage.error('加载商品失败，请重试');
        })
}

// 搜索商品
const handleSearch = () => {
    alert("功能炒鸡开发中..")
}

const del = (val) => {
    // 二次确认
    ElMessageBox.confirm(
        '确定要删除该商品吗？删除后不可恢复',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        axios.get(`api/deleteProduct/${val}`)
            .then(res => {
                if (res.code === 200) {
                    ElMessage({


                        message: "删除成功~",
                        type: "success",
                        duration: 1500,
                        onClose: () => {
                            init() // 重新加载列表
                        }
                    })
                } else {
                    ElMessage.error(res.msg || '删除失败');
                }
            })
            .catch(err => {
                console.error('删除失败:', err);
                ElMessage.error('删除失败，请重试');
            })
    }).catch(() => {
        // 取消删除
        ElMessage({
            type: 'info',
            message: '已取消删除'
        });
    });
}

//添加商品弹窗
const handleAdd = (row) => {
    addForm.productId=row.productId;
    addForm.productName=row.productName;
    addForm.listPrice=row.listPrice;
    addForm.actualPrice=row.actualPrice;
    addForm.stock=row.stock;
    addForm.shortDesc=row.shortDesc;
    addForm.longDesc=row.longDesc;
    isAddDialogVisible.value = true;
}

// 提交添加数据
const handleAddProduct = () => {
    axios.post("/api/addProduct", addForm)
        .then(res => {
            if (res.code === 200) {
                ElMessage({
                    message: "添加成功~",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                        isAddDialogVisible.value = false;
                        init() // 重新加载列表
                    }
                })
            } else {
                ElMessage.error(res.msg || '添加失败');
            }
        })
        .catch(err => {
            console.error('添加失败:', err);
            ElMessage.error('添加失败，请重试');
        })
}

// 打开编辑弹窗
const handleEdit = (row) => {
    // 填充表单数据
    editForm.productId = row.productId;
    editForm.productName = row.productName;
    editForm.listPrice = row.listPrice;
    editForm.actualPrice = row.actualPrice;
    editForm.stock = row.stock;
    editForm.shortDesc = row.shortDesc;
    isEditDialogVisible.value = true;
}

// 提交更新
const handleUpdate = () => {
    axios.post("/api/updateProduct", editForm)
        .then(res => {
            if (res.code === 200) {
                ElMessage({
                    message: "更新成功~",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                        isEditDialogVisible.value = false;
                        init() // 重新加载列表
                    }
                })
            } else {
                ElMessage.error(res.msg || '更新失败');
            }
        })
        .catch(err => {
            console.error('更新失败:', err);
            ElMessage.error('更新失败，请重试');
        })
}

const goodsList = ref([
    {
        productId: 0,
        productName: '',
        listPrice: 0,
        image1: '',
        image2: '',
        image3: '',
        shortDesc: '',
        longDesc: '',
        listedAt: '',
        stock: 0,
        collects: 0,
        sales: 0,
        discount: 0,
        actualPrice: 0,
    }
]);

const jump = (val) => {
    pages.page = val;
    init();
}


</script>

<style scoped>
.products-management {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.page-title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e5e7eb;
}

.operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 10px;
}

.search-box {
    display: flex;
    gap: 10px;
    align-items: center;
}

.search-input {
    width: 300px;
}

.products-table {
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
}

.product-img {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
}

.btn-edit {
    margin-right: 5px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 10px 0;
}

/* 适配响应式 */
@media (max-width: 768px) {
    .operation-bar {
        flex-direction: column;
        align-items: flex-start;
    }

    .search-input {
        width: 100%;
    }

    .search-box {
        width: 100%;
    }
}
</style>
